<?php
namespace Deyi\Weixin;

    //即时到帐支付应答类
    //============================================================================
    //api说明：
    //getKey()/setKey(),获取/设置密钥
    //getParameter()/setParameter(),获取/设置参数值
    //getAllParameters(),获取所有参数
    //isTenpaySign(),是否财付通签名,true:是 false:否
    //getDebugInfo(),获取debug信息
//============================================================================

class ResponseHandler
{
    //密钥
    private $key = '';

    //应答的参数
    private $parameters = [];

    //debug信息
    private $debugInfo = '';

    //初始构造函数
    function __construct($key)
    {

        $this->key = $key;
        //$this->gateUrl = "https://wpay.tenpay.com/wx_pub/v1.0/wx_app_api.cgi";

        /* GET */
        foreach ($_GET as $k => $v) {
            $this->parameters[$k] = $v;
        }
        /* POST */
        foreach ($_POST as $k => $v) {
            $this->parameters[$k] =  $v;
        }
    }

    //获取参数值
    function getParameter($parameter)
    {
        return $this->parameters[$parameter];
    }

    //获取所有请求的参数
    function getAllParameters()
    {
        return $this->parameters;
    }

    function isTenpaySign()
    {
        $signPars = "";

        $orgsignPars = print_r($this->parameters,true);

        ksort($this->parameters);
        foreach ($this->parameters as $k => $v) {
            if ( !in_array($k,["sign",'_url']) && "" != $v) {
                $signPars .= $k . "=" . $v . "&";
            }
        }
        $signPars .= "key=" . $this->key;

        $sign = strtolower(md5($signPars));

        $tenpaySign = strtolower($this->getParameter("sign"));

        //debug信息
        $this->debugInfo = "orgsignpars: $orgsignPars \n\r\n\r $signPars  \n\r\n\r sign:" . $sign . " tenpaySign:" . $this->getParameter("sign");

        return $sign == $tenpaySign;

    }

    /**
     *显示处理结果。
     *
     * @param $show_url 显示处理结果的url地址,绝对url地址的形式(http://www.xxx.com/xxx.php)。
     */
    function doShow($show_url)
    {
        $strHtml = "<html><head>\r\n" .
            "<meta name=\"TENCENT_ONLINE_PAYMENT\" content=\"China TENCENT\">" .
            "<script language=\"javascript\">\r\n" .
            "window.location.href='" . $show_url . "';\r\n" .
            "</script>\r\n" .
            "</head><body></body></html>";

        echo $strHtml;

        exit;
    }


    //获取debug信息
    function getDebugInfo()
    {
        return $this->debugInfo;
    }
}

?>